<?php
namespace zhtfrontend\modules\sitepadapi\controllers;
/**
 * Created by PhpStorm.
 * User: dongxiaofeng
 * Date: 2017/3/22
 * Time: 14:16
 */
use common\components\helpers\Fun;
use common\models\datas\Customer;
use zhtfrontend\models\datas\Admin;
use zhtfrontend\models\datas\Teacher;
use zhtfrontend\modules\sitepadapi\components\rest\ActiveController;
use yii\data\ArrayDataProvider;
use yii\db\Query;
use yii\filters\Cors;
use yii\web\Response;
use yii\web\ForbiddenHttpException;
use yii\web\NotFoundHttpException;
use yii\helpers\ArrayHelper;

class AdminuserController extends ActiveController
{
    public $modelClass = 'zhtfrontend\models\datas\Admin';

    public $serializer = [
        'class' => 'zhtfrontend\modules\sitepadapi\components\rest\Serializer',
        'collectionEnvelope' => 'items',
    ];

    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_JSON;
        $behaviors['corsFilter'] = [
            'class' => Cors::className(),
            'cors' => [
                'Origin' => ['*'],
                'Access-Control-Allow-Origin' => ['*'],
                'Access-Control-Request-Method' => ['POST', 'PUT', 'GET', 'HEAD', 'OPTIONS'],
                'Access-Control-Request-Headers' => ['Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With'],
                'Access-Control-Allow-Credentials' => true,
                'Access-Control-Max-Age' => 3600,
                'Access-Control-Expose-Headers' => ['X-Pagination-Current-Page'],
            ],
        ];
        return $behaviors;
    }

    public function actions()
    {
        $actions = parent::actions();
        unset($actions['index'], $actions['create'], $actions['update'], $actions['delete'], $actions['view']);
        return $actions;
    }

    //教师或班主任或管理员administrator class_teacher teache_teacher
    public function actionLogin($rolename = 'teache_teacher'){

        //var_dump('121212');die;
        $data = \Yii::$app->request->post();
        $tel = ArrayHelper::keyExists('tel', $data) ? $data['tel'] : '';
        $password = ArrayHelper::keyExists('password', $data) ? $data['password'] : '';
        if (empty($tel) || empty($password)) {
            try {
                throw new ForbiddenHttpException('用户名或密码不能为空');
            } catch (ForbiddenHttpException $e) {
                return ['statusCode' => $e->statusCode, 'message' => 'error', 'items' => $e->getMessage()];
            }
        }else{
            $teacher_admin = (new Query())->select('*')->from('{{%admin}}')->where(['username'=>$tel])->one(Fun::getSiteDb());
            if (empty($teacher_admin)) {
                try {
                    throw new NotFoundHttpException('该用户不存在');
                } catch (NotFoundHttpException $e) {
                    return ['statusCode' => $e->statusCode, 'message' => 'error', 'items' => $e->getMessage()];
                }
            }else{
                if($rolename == $teacher_admin['role']){
                    if (\Yii::$app->getSecurity()->validatePassword($password, $teacher_admin['password'])) {
                        \Yii::$app->session->set('user_id', $teacher_admin['id']);
                        $data = [
                            'admin_id' => $teacher_admin['id'],
                            'teacher_id' => $teacher_admin['teacher_id'],
                            'role_name' => $teacher_admin['role']
                        ];
                        return ['statusCode'=>200,'message'=>'success','items' => $data];
                    } else {
                        try {
                            throw new ForbiddenHttpException('密码错误');
                        } catch (ForbiddenHttpException $e) {
                            return ['statusCode' => $e->statusCode, 'message' => 'error', 'items' => $e->getMessage()];
                        }
                    }
                }else{
                    $item_message = '当前手机号用户与所属权限不匹配';
                    return ['statusCode' => 200, 'message' => 'error', 'items' => $item_message];
                }
            }
        }
    }

    public function actionView($id)
    {
        $admin = $this->findModel($id);
        $teacher = (new Query())->select('*')->from('{{%teacher}}')
            ->where(['id'=>$admin->teacher_id])->one(Fun::getSiteDb());
        $data = [
            'admin_name' => $admin->name,
            'admin_logo' => $admin->logo,//$teacher['img']
        ];
        return ['statusCode' => 200, 'message' => 'success', 'items' => $data];
    }

    protected function findModel($id)
    {
        $modelClass = $this->modelClass;
        if (($model = $modelClass::findOne($id)) !== null) {
            return $model;
        } else {
            try {
                throw new NotFoundHttpException('信息不存在');
            } catch (NotFoundHttpException $e) {
                return ['status' => 0, 'message' => 'error', 'result' => $e->getMessage()];
            }
        }
    }

    public function actionGetteacherid($admin_id){
        $admin = (new Query())->select('*')->from('{{%admin}}')->where(['id' => $admin_id])->one(Fun::getSiteDb());
        if(!empty($admin)){
            return ['statusCode' => 200, 'message' => 'success', 'items' => $admin['teacher_id']];
        }else{
            return ['statusCode' => 0, 'message' => 'fail', 'items' => null];
        }
    }

    /*获取班主任明下的老师id们*/
    public function actionGetheadteacherid($admin_id){
        $admin = (new Query())->select('*')->from('{{%admin}}')->where(['id' => $admin_id,'role'=>'class_teacher'])->one(Fun::getSiteDb());
        if(!empty($admin)){//如果存在班主任身份的admin
            return ['statusCode' => 200, 'message' => 'success', 'items' => $admin['teacher_id']];
        }
    }

    /*获取原始密码*/
    public function actionCheckoriginpwd(){
        $admin_id = \Yii::$app->request->get('admin_id')?\Yii::$app->request->get('admin_id'):null;
        $get_pwd = \Yii::$app->request->get('origin_pwd')?\Yii::$app->request->get('origin_pwd'):null;
        if(empty($admin_id)){
            try {
                throw new NotFoundHttpException('传入id不可为空');
            } catch (NotFoundHttpException $e) {
                return ['statusCode'=>$e->statusCode,'message'=>'传入数据有误','items'=>$e->getMessage()];
            }
        }
        $admin = Admin::findOne($admin_id);
        if(empty($admin)){
            try {
                throw new NotFoundHttpException('用户不存在');
            } catch (NotFoundHttpException $e) {
                return ['statusCode'=>$e->statusCode,'message'=>'用户不存在','items'=>$e->getMessage()];
            }
        }
        if(!empty($get_pwd)){
            if($admin->validatePassword($get_pwd)){
                $data = ['result'=>'success'];
                return ['statusCode'=>200,'items'=>$data];
            }else{
                $data = ['result'=>'error'];
                return ['statusCode'=>200,'items'=>$data];
            }
        }else{
            try {
                throw new NotFoundHttpException('密码不可为空');
            } catch (NotFoundHttpException $e) {
                return ['statusCode'=>$e->statusCode,'message'=>'密码不可为空','items'=>$e->getMessage()];
            }
        }
    }

    /*
     * 密码修改
     */
    public function actionChangecustomerpwd(){
        $admin_id = \Yii::$app->request->get('admin_id')?\Yii::$app->request->get('admin_id'):null;
        $newpwd = \Yii::$app->request->get('new_password')?\Yii::$app->request->get('new_password'):null;
        if(!empty($admin_id) && !empty($newpwd)){
            $admin = Admin::findOne($admin_id);
            $admin->password = \Yii::$app->security->generatePasswordHash($newpwd);
            $admin->save(false);
            $data = ['result'=>'success'];
            return ['statusCode'=>200,'items'=>$data];
        }else{
            try {
                throw new NotFoundHttpException('传入数据有误');
            } catch (NotFoundHttpException $e) {
                return ['statusCode'=>$e->statusCode,'message'=>'传入数据有误','items'=>$e->getMessage()];
            }
        }
    }

    /*更改用户头像*/
    public function actionChangecustomerportrait($customer_id){

        $model = Customer::findOne($customer_id);
        $headimgurl = \Yii::$app->request->get('headimgurl');
        if(empty($model) || empty($headimgurl)){
            throw new NotFoundHttpException('信息不存在');
        }
        $model->logo = $headimgurl;
        if($model->save(false)){
            $data = ['result'=>'success'];
            return ['statusCode'=>200,'items'=>$data];
        }
    }

    /*
 * 绑定手机号功能-
 * 输入手机号正确与否判断1. 不能和原有手机号相同 2. 不能和表中除自己之外的手机号重合
 */
    public function actionCheckbindphone(){
        $admin_id = \Yii::$app->request->get('admin_id')?\Yii::$app->request->get('admin_id'):null;
        $telephone = \Yii::$app->request->get('telephone')?\Yii::$app->request->get('telephone'):null;
        if(empty($admin_id)){
            try {
                throw new NotFoundHttpException('传入数据有误');
            } catch (NotFoundHttpException $e) {
                return ['statusCode'=>$e->statusCode,'message'=>'传入数据有误','items'=>$e->getMessage()];
            }
        }

        $admin = Admin::findOne($admin_id);
        if(!empty($admin)){
            if(!empty($admin['mobile'])){
                if($telephone == $admin['mobile']){
                    $data = ['result'=>'samewithorigin','msg'=>'输入手机号不可与原有手机号相同'];
                    return ['statusCode'=>200,'items'=>$data];
                }
            }
            /*判断是否和其他会员手机号冲突*/
            $existteleadmin = Admin::find()->where(['not',['id' => $admin_id]])->andWhere(['mobile'=>$telephone])->one();
            if(!empty($existteleadmin)){
                $data = ['result'=>'haveused','msg'=>'该手机号已被其他用户占用'];
                return ['statusCode'=>200,'items'=>$data];
            }
            $data = ['result'=>'success','msg'=>'手机号可被正常使用'];
            return ['statusCode'=>200,'items'=>$data];

        }else{
            try {
                throw new NotFoundHttpException('用户不存在');
            } catch (NotFoundHttpException $e) {
                return ['statusCode'=>$e->statusCode,'message'=>'用户不存在','items'=>$e->getMessage()];
            }
        }
    }

    /*
     * 生成验证码
     */
    public function actionGetcode(){
        $maxcount_code = 5;
        $telenumber = \Yii::$app->request->get('telephone')?\Yii::$app->request->get('telephone'):null;
        $telecode_info = \Yii::$app->cache->get('smscode_'.$telenumber);
        if(empty($telenumber)){
            try {
                throw new NotFoundHttpException('手机号不可为空');
            } catch (NotFoundHttpException $e) {
                return ['statusCode'=>$e->statusCode,'message'=>'手机号不可为空','items'=>$e->getMessage()];
            }
        }
        if($telecode_info){//缓存中已经存在了该手机号;一分钟的倒计时还是放到app那端吧 这边用session不对劲
            $now = date('Y-m-d');
            $codeinfo = unserialize($telecode_info);

            $count = $codeinfo['count'] ? $codeinfo['count'] : 0;//每天只能获取五次
            $cachedate = $codeinfo['date'];
            if ($now == $cachedate) {//当前的日期和缓存中该手机号的日期相同
                if ($count >= $maxcount_code) {//是否超过每天限制的获取次数
                    $data['result'] = 'failed';
                    $data['msg'] = '此手机号于今天已经获取' . $maxcount_code . '次验证码，禁止再次获取';
                    return ['statusCode'=>200,'items'=>$data];
                }
            } else {//缓存中的日期不是今天，更新获取次数为0，日期为今天
                $count = 0;
                $codeinfo = array(
                    'count' => $count,
                    'date' => $now
                );
                $codeinfoser = serialize($codeinfo);
                \Yii::$app->cache->set('smscode_'.$telenumber, $codeinfoser, 3600 * 24);
            }
        }else{
            $codeinfo = array(
                'count' => 0,
                'date' => date('Y-m-d')
            );
            $codeinfoser = serialize($codeinfo);
            \Yii::$app->cache->set('smscode_'.$telenumber, $codeinfoser, 3600 * 24);
        }

        $code = $this->generateCode();
        $res['mobile'] = $telenumber;
        $res['content'] = "您的验证码是：【" . $code . "】。请不要把验证码泄露给其他人。";
        $send_result = \Yii::$app->smsSend->send($res);
        if(isset($send_result['code']) && $send_result['code'] == '2'){

            $phonecode = \Yii::$app->cache->get('smscode_'.$telenumber);
            $phonecode = unserialize($phonecode);
            $phonecode['count'] = $phonecode['count'] + 1;
            $phonecode = serialize($phonecode);
            \Yii::$app->cache->set('smscode_'.$telenumber, $phonecode, 3600 * 24);

            $data['result'] = 'success';
            $data['msg'] = $send_result['msg'];
            $data['code'] = $code;
            \Yii::$app->cache->set($telenumber.'_code',$code,60*5);//以手机号为辨认符号来保存验证码
            $cachecode = \Yii::$app->cache->get($telenumber.'_code');
            return ['statusCode'=>200,'items'=>$data];
        }else{
            $data['result'] = 'failed';
            $data['msg'] = $send_result['msg'];

            return ['statusCode'=>200,'items'=>$data];
        }
    }
    private function generateCode()
    {
        return rand(1000, 9999);
    }

    /*
    * 绑定手机号功能-
    * 获取手机号
    */
    public function actionGetmobile(){
        //substr_replace($customer['mobile'],'****',3,4):'')
        $admin_id = \Yii::$app->request->get('admin_id')?\Yii::$app->request->get('admin_id'):null;
        if(!empty($admin_id)){
            $admin = Admin::findOne($admin_id);
            $tele = $admin->mobile;
            if(!empty($tele)){
                $result_mobile = substr_replace($tele,'****',3,4);
                $data = ['data'=>$result_mobile];
                return ['statusCode'=>200,'items'=>$data];
            }else{
                $data = ['data'=>null];
                return ['statusCode'=>200,'items'=>$data];
            }
        }else{
            try {
                throw new NotFoundHttpException('传入数据有误');
            } catch (NotFoundHttpException $e) {
                return ['statusCode'=>$e->statusCode,'message'=>'传入数据有误','items'=>$e->getMessage()];
            }
        }
    }

    /** 验证手机验证码*/
    public function actionCheckverifycode(){
        $telenumber = \Yii::$app->request->get('telephone')?\Yii::$app->request->get('telephone'):null;
        $code = \Yii::$app->request->get('code')?\Yii::$app->request->get('code'):null;
        if(empty($telenumber) || empty($code)){
            try {
                throw new NotFoundHttpException('输入数据有误');
            } catch (NotFoundHttpException $e) {
                return ['statusCode'=>$e->statusCode,'message'=>'输入数据有误','items'=>$e->getMessage()];
            }
        }

        $code_cachekey = $telenumber.'_code';

        $cachecode = \Yii::$app->cache->get($code_cachekey);

        if(empty($cachecode)){
            $data['result'] = 'failed';
            return ['statusCode'=>200,'items'=>$data];
        }else{
            if($cachecode == $code){
                $data['result'] = 'success';
                return ['statusCode'=>200,'items'=>$data];
            }else{
                $data['result'] = 'failed';
                return ['statusCode'=>200,'items'=>$data];
            }
        }
    }

    /** 绑定手机号 */
    public function actionBindphone(){
        $admin_id = \Yii::$app->request->get('admin_id')?\Yii::$app->request->get('admin_id'):null;
        $telephone = \Yii::$app->request->get('telephone')?\Yii::$app->request->get('telephone'):null;
        if(empty($admin_id) || empty($telephone)){
            try {
                throw new NotFoundHttpException('传入数据不可为空');
            } catch (NotFoundHttpException $e) {
                return ['statusCode'=>$e->statusCode,'message'=>'传入数据不可为空','items'=>$e->getMessage()];
            }
        }
        $admin = Admin::findOne($admin_id);
        if(empty($admin)){
            try {
                throw new NotFoundHttpException('用户不存在');
            } catch (NotFoundHttpException $e) {
                return ['statusCode'=>$e->statusCode,'message'=>'用户不存在','items'=>$e->getMessage()];
            }
        }else{
            $admin->mobile = $telephone;
            $admin->save(false);
            $data = ['result'=>'success'];
            return ['statusCode'=>200,'items'=>$data];
        }
    }

    /*更改用户头像*/
    public function actionChangeheadportrait($admin_id){
        $modelClass = $this->modelClass;
        $model = $modelClass::findOne($admin_id);
        $headimgurl = \Yii::$app->request->get('headimgurl');
        if(empty($model) || empty($headimgurl)){
            throw new NotFoundHttpException('信息不存在');
        }
        $model->logo = $headimgurl;
        if($model->save(false)){
            if(!empty($model->teacher_id)){
                $teacher = Teacher::findOne($model->teacher_id);
                if(!empty($teacher)){
                    $teacher->img = $headimgurl;
                    $teacher->save(false);
                }
            }
            $data = ['result'=>'success'];
            return ['statusCode'=>200,'items'=>$data];
        }
    }

    public function actionChangeadminname(){
        $admin_id = \Yii::$app->request->get('admin_id')?\Yii::$app->request->get('admin_id'):null;
        $admin_name = \Yii::$app->request->get('admin_name')?\Yii::$app->request->get('admin_name'):null;
        if(empty($admin_id) || empty($admin_name)){
            try {
                throw new NotFoundHttpException('传入数据不可为空');
            } catch (NotFoundHttpException $e) {
                return ['statusCode'=>$e->statusCode,'message'=>'传入数据不可为空','items'=>$e->getMessage()];
            }
        }
        $admin = Admin::findOne($admin_id);
        if(empty($admin)){
            try {
                throw new NotFoundHttpException('用户不存在');
            } catch (NotFoundHttpException $e) {
                return ['statusCode'=>$e->statusCode,'message'=>'用户不存在','items'=>$e->getMessage()];
            }
        }else{
            $admin->name = $admin_name;
            $admin->save(false);
            $data = ['result'=>'success'];
            return ['statusCode'=>200,'items'=>$data];
        }
    }
}